package com.sea.onlinejudge.common.utils;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class JwtTokenUtil {
    @Value("${jwtconfig.jwt.secretKey}")
    private String secretKey;
    @Value("${jwtconfig.jwt.exp}")
    private long exp;
    @Value("${jwtconfig.jwt.header}")
    private String header;

    /**
     * 生成JWT, obj为签发的接收人
     * @param obj
     * @return
     */
    public String builderToken(Object obj) {
        Date nowDate = new Date();
        //过期时间
        Date expirDate = new Date(nowDate.getTime() + exp*1000);

        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setAudience(obj.toString())
                .setIssuedAt(nowDate)       //签发时间
                .setExpiration(expirDate)   //过期时间
                .signWith(SignatureAlgorithm.HS512, secretKey)
                .compact();
    }

    /**
     * 解析JWT中间的payload
     * @param token
     * @return
     * @throws JwtException
     */
    public Claims getClaims(String token) {

        return  Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 判断是否过期，true为过期
     * @param date
     * @return
     */
    public boolean isTokenExpired(Date date) {
        return (date).before(new Date());
    }


    public String getSecretKey() {
        return secretKey;
    }
    public long getExp() {
        return exp;
    }
    public String getHeader() {
        return header;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public void setExp(long exp) {
        this.exp = exp;
    }

    public void setHeader(String header) {
        this.header = header;
    }
}
